package com.feihong.txgw.ui.activity.setting;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.TypedValue;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.blankj.utilcode.util.LogUtils;
import com.feihong.txgw.R;
import com.feihong.txgw.http.HttpTools;
import com.feihong.txgw.http.RefreshToken;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.message.QueryUnReadMsgNumMessage;
import com.feihong.txgw.message.SystemMsgMessage;
import com.feihong.txgw.ui.activity.base.BaseActivity;
import com.feihong.txgw.utils.manage.ThreadPoolManager;
import com.feihong.txgw.utils.sign.SignToken;
import com.feihong.txgw.view.WebView4Scroll;
import com.just.agentweb.AgentWeb;
import com.xiaomi.mipush.sdk.MiPushMessage;
import com.xiaomi.mipush.sdk.PushMessageHelper;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import butterknife.BindView;

/*
*消息详情页*/
public class MessageDetailsActivity extends BaseActivity {


    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.top_back_layout)
    RelativeLayout topBackLayout;
    @BindView(R.id.webviewframe)
    RelativeLayout webviewframe;
    @BindView(R.id.swiperefreshlayout)
    SwipeRefreshLayout swiperefreshlayout;
    private AgentWeb mAgentWeb;
    private String homeUrl = "/App/Message/system_info",id;
    private String msg_id;
    public static int  MESSAGE_LIST_TYPE = 1; // 消息列表界面跳转而来
    public static String MESSAGE_TYPE = "msg_type";
    private int msgType = 1; // 0  状态栏消息点击跳转而来   1 消息列表界面跳转而来

    @BindView(R.id.connect_net_error_layout)
    LinearLayout mConnectErrorLayout;
    @BindView(R.id.re_query_data_layout)
    LinearLayout mRequeryDataBtn;
    private AgentWeb.PreAgentWeb mPreAgentWeb;
    private HashMap<String, String> mParams ;
    private Handler mHandler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(activityIsDestory()){
                return;
            }
            if(msg.what == 10){
                loadPage();
            }else if(msg.what == 11){
                mConnectErrorLayout.setVisibility(View.VISIBLE);
            }
        }
    };

    @Override
    public void setTheme() {

    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_message_details;
    }

    @Override
    public void initView(Bundle savedInstanceState) {

        mParams = new HashMap<>();
        Intent Ingt = getIntent();
        // 判断消息类型   普通消息  还是推送消息
        if(MESSAGE_LIST_TYPE == Ingt.getIntExtra(MESSAGE_TYPE,0)){
            msgType = 1;
            id = Ingt.getStringExtra("id");
        }else {
            msgType = 0;
            MiPushMessage miPushMessage = (MiPushMessage) Ingt.getSerializableExtra(PushMessageHelper.KEY_MESSAGE);
            msg_id = miPushMessage.getMessageId();
        }
        setBackButtonFinish();
        setPageTitle("消息详情");
        mRequeryDataBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mConnectErrorLayout.setVisibility(View.GONE);
                refreshToken();
            }
        });
        //设置刷新时动画的颜色，可以设置4个
        swiperefreshlayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
        swiperefreshlayout.setColorSchemeResources(R.color.appRed,
                android.R.color.holo_red_light, android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
        swiperefreshlayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));
        swiperefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshToken();
            }
        });
        //同步 Cookie
        //AgentWebConfig.syncCookies("http://www.djml.com","ID=XXXX")
        swiperefreshlayout.setRefreshing(true);

        WebView4Scroll webView4Scroll = new WebView4Scroll(MessageDetailsActivity.this, swiperefreshlayout);
        webView4Scroll.setVerticalScrollBarEnabled(false);
        // Activity用法

        mPreAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(webviewframe, new RelativeLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setWebChromeClient(mWebChromeClient).setWebView(webView4Scroll)
                .setWebViewClient(mWebViewClient)
                .setMainFrameErrorView(R.layout.agentweb_errorlayout,R.id.agentweb_re_query_data_layout)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                .createAgentWeb()
                .ready();
    }

    //WebViewClient
    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return true;
        }
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return true;
        }
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            swiperefreshlayout.setRefreshing(false);
            Intent Ingt = getIntent();
            if("2".equals(Ingt.getStringExtra("is_read"))){
                EventBus.getDefault().post(new SystemMsgMessage());
                EventBus.getDefault().post(new QueryUnReadMsgNumMessage());
            }
        }
        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    };
    //WebChromeClient
    private WebChromeClient mWebChromeClient = new WebChromeClient() {
    };

    @Override
    public void bindData() {

        refreshToken();

    }

    private void loadPage() {
        mParams.clear();
        if(id != null){
            mParams.put("id",id);
        }else {
            mParams.put("xm_msg_id",msg_id);
        }
        String params = new SignToken().setSigen(mParams);
        String url = HttpTools.HTTP_HOME +homeUrl+"?"+params;
        LogUtils.i(TAG,"消息详情url:"+url);
        mAgentWeb = mPreAgentWeb.go(url); // url

        //屏蔽长按弹出复制按钮
        mAgentWeb.getWebCreator().getWebView().setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });

        if(mAgentWeb != null){
            mAgentWeb.getWebLifeCycle().onResume();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void refreshToken(){
        ThreadPoolManager.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                if(RefreshToken.getInstance().RetrofitRefreshTokenForGet()){
                    Message message = new Message();
                    message.what = 10;
                    mHandler.sendMessage(message);
                }
            }
        });
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mAgentWeb != null){
            mAgentWeb.destroy();
        }
        if(mHandler != null && mHandler.getLooper() == Looper.getMainLooper()){
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    public void onBackPressedSupport() {
        super.onBackPressedSupport();
        finish();
    }
}
